package magnet.processor.instances.aspects.disposer;

import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.TypeName;
import com.squareup.javapoet.TypeSpec;
import magnet.processor.instances.FactoryType;

import javax.lang.model.element.Modifier;

public class DisposeMethodGenerator {

    private MethodSpec.Builder methodBuilder = null;

    public void visitFactoryClass(FactoryType factoryType) {
        if (factoryType == null) return;
        if (factoryType.getDisposerMethodName() == null) {
            methodBuilder = null;
        } else {
            methodBuilder = MethodSpec.methodBuilder("dispose")
                    .addAnnotation(Override.class)
                    .addModifiers(Modifier.PUBLIC)
                    .returns(TypeName.VOID)
                    .addParameter(factoryType.getInterfaceType(), "instance")
                    .addStatement(
                            "(($T) instance).$L()",
                            factoryType.getImplementationType(), factoryType.getDisposerMethodName()
                    );
        }
    }

    public void generate(TypeSpec.Builder typeBuilder) {
        if (methodBuilder == null) return;
        typeBuilder.addMethod(methodBuilder.build());
    }
}
